package com.yuanfeng.userms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.userms.dto.RegisterSellerDTO;
import com.yuanfeng.userms.entity.UserRongyunInfoEntity;
import com.yuanfeng.userms.entity.UserSellerBaseEntity;
import com.yuanfeng.userms.mapper.UserRongyunInfoMapper;
import com.yuanfeng.userms.mapper.UserSellerBaseMapper;
import com.yuanfeng.userms.service.UserRongyunInfoService;
import com.yuanfeng.userms.vo.RongTokenResultVO;
import io.rong.RongCloud;
import io.rong.methods.user.User;
import io.rong.models.Result;
import io.rong.models.response.TokenResult;
import io.rong.models.user.UserModel;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 *
 */
@Service
public class UserRongyunInfoServiceImpl extends ServiceImpl<UserRongyunInfoMapper, UserRongyunInfoEntity>
    implements UserRongyunInfoService{

    @Autowired
    private UserSellerBaseMapper userSellerBaseMapper;

    // 线上
    private static final String appKey = "pwe86ga5pswh6";
    private static final String appSecret = "q8tNkv1ClGax3";
    @Override
    public ResponseResult registerUserSeller(RegisterSellerDTO param) throws Exception {
        //查询店铺的userId
        String userId = userSellerBaseMapper.selectOne(new LambdaQueryWrapper<UserSellerBaseEntity>()
                        .eq(UserSellerBaseEntity::getShopId,param.getShopId())
                        .eq(UserSellerBaseEntity::getSellerIsAdmin, CommonType.commonStatus.YES.getCode())).getSellerId();
        String id = ""; // 用户唯一标识，支持大小写英文字母、数字、部分特殊符号 + | = - _ 的组合方式，最大长度 64 字节。
        String name = ""; //用户名称，最大长度 128 字节。用来在 Push 推送时显示用户的名称。
        String portrait = ""; //用户头像地址，最大长度 1024 字节，类型不限制, 建议: jpg、png
        if (userId != null || userId.length() != 0) {
            id = userId;
        } else {
            return ResponseResult.fail(BizCodeEnume.USER_DOES_NOT_EXIST);
        }

        //获取对应的用户昵称
        if (param.getName() == null && StringUtils.isEmpty(param.getName())) {

            return ResponseResult.fail(BizCodeEnume.USER_NICKNAME_NOT_OBTAINED);
        } else {
            name = param.getName();
        }
        //获取对应的用户头像路径
        if (param.getPortrait() == null && StringUtils.isEmpty(param.getPortrait())) {
            return ResponseResult.fail(BizCodeEnume.USER_PROFILE_NOT_OBTAINED);
        } else {
            portrait = param.getPortrait();

        }
        RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
        User User = rongCloud.user;


        // 注册用户，生成用户在融云的唯一身份标识 Token
        UserModel userModel = new UserModel().setId(id).setName(name).setPortrait(portrait);
        TokenResult result = User.register(userModel);

        RongTokenResultVO rongTokenResult = new RongTokenResultVO();

        rongTokenResult.setToken(result.getToken());
        rongTokenResult.setUserId(result.getUserId());
        // 刷新用户信息方法
        Result refreshResult = User.update(userModel);
        //证明注册成功  将店铺的注册的信息保存到数据库
        if (result.getToken() != null) {
            //先去查询数据库里是否存在 如果存在做更细操作
            Integer varId = Integer.valueOf(this.baseMapper.selectOne(new LambdaQueryWrapper<UserRongyunInfoEntity>()
                    .eq(UserRongyunInfoEntity::getUserid,result.getUserId())).getId().toString());
            if (varId != null) {
                //表示存在做更新操作
                Integer res = this.baseMapper.update(null,new LambdaUpdateWrapper<UserRongyunInfoEntity>()
                              .eq(UserRongyunInfoEntity::getId,String.valueOf(varId))
                              .set(UserRongyunInfoEntity::getUserid,result.getUserId())
                              .set(UserRongyunInfoEntity::getShopid,param.getShopId()));

                if (res == 0) {
                    return ResponseResult.fail(BizCodeEnume.OPERATION_FAILED);
                }
            } else {
                UserRongyunInfoEntity entity=new UserRongyunInfoEntity();
                entity.setUserid(result.getUserId());
                entity.setShopid(Integer.valueOf(param.getShopId()));
                //表示不存在做插入操作
                Integer res = this.baseMapper.insert(entity);
                if (res == 0) {
                    return ResponseResult.fail(BizCodeEnume.OPERATION_FAILED);
                }
            }

            return ResponseResult.success(rongTokenResult);
        } else {
            return ResponseResult.fail(BizCodeEnume.OPERATION_FAILED);
        }
    }
}




